<template>
  <div class="paper-list-container">
    <div class="paper-header">
      <h2>试卷管理</h2>
      <div class="paper-tools">
        <label for="">学科：</label>
        <el-select 
          v-model="paperForm.subjectId" 
          placeholder="请选择学科" 
          @change="handleSubjectChange"
          class="subject-select"
        >
          <el-option 
            v-for="subject in subjects" 
            :key="subject.id" 
            :label="subject.name" 
            :value="subject.id"
          />
        </el-select>
        <el-button type="primary" @click="handleCreatePaper">
          <el-icon><Plus /></el-icon>创建试卷
        </el-button>
      </div>
    </div>

    <div class="paper-content">
      <!-- 空状态 -->
      <el-empty 
        v-if="paperList.length === 0 && !loading" 
        description="暂无试卷数据"
      >
        <el-button type="primary" @click="handleCreatePaper">立即创建</el-button>
      </el-empty>
      
      <!-- 表格区域 -->
      <el-table
        v-else
        :data="paperList"
        style="width: 100%"
        border
        v-loading="loading"
        row-key="paperId"
        :header-cell-style="{background:'#f5f7fa', color: '#606266'}"
      >
        <el-table-column prop="paperName" label="试卷名称" min-width="150">
          <template #default="scope">
            <span class="paper-name">{{ scope.row.paperName }}</span>
          </template>
        </el-table-column>
        
        <el-table-column label="试题数量" align="center" width="120">
          <template #default="scope">
            <el-tag type="info">
              {{ scope.row.questionIds ? scope.row.questionIds.split(',').length : 0 }} 题
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column label="难度" align="center" width="120">
          <template #default="scope">
            <el-tag :type="getDifficultyTag(scope.row.difficulty)">
              {{ getDifficultyText(scope.row.difficulty) }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column label="题型分布" min-width="200">
          <template #default="scope">
            <div class="question-types">
              <el-tag 
                v-for="(type, index) in getQuestionTypes(scope.row.typeSet)" 
                :key="index"
                effect="plain"
                class="question-type-tag"
              >
                {{ type }}
              </el-tag>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column label="操作" min-width="150" align="center">
          <template #default="scope">
            <el-button 
              size="small" 
              type="primary" 
              @click="handleViewPaper(scope.row)"
            >
              查看
            </el-button>
            <el-button 
              size="small" 
              type="success" 
              @click="handleEditPaper(scope.row)"
            >
              编辑
            </el-button>
            <el-button 
              size="small" 
              type="primary"
              :loading="exportLoading && scope.row.paperId === exportingPaperId" 
              @click="handleexportPaper(scope.row)"
            >
              <!-- <el-icon><Download /></el-icon>-->
              导出 
            </el-button>
            <el-popconfirm
              title="确定删除此试卷吗？"
              @confirm="handleDeletePaper(scope.row.paperId)"
            >
              <template #reference>
                <el-button size="small" type="danger">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container" v-if="paperList.length > 0">
        <el-pagination
          v-model:current-page="paperForm.pageNum"
          v-model:page-size="paperForm.pageSize"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 预览对话框 -->
    <el-dialog
      v-model="previewDialogVisible"
      title="试卷预览"
      width="80%"
      :destroy-on-close="true"
    >
      <paper-preview 
        v-if="currentPaper"
        :paper="currentPaper" 
        :questions="currentQuestions"
      />
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="previewDialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="handleEditPaper(currentPaper)">编辑试卷</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 添加导出信息输入对话框 -->
    <el-dialog
      v-model="exportDialogVisible"
      title="填写试卷信息"
      width="50%"
      :destroy-on-close="true"
    >
      <el-form 
        :model="exportForm" 
        label-width="100px"
        :rules="exportFormRules"
        ref="exportFormRef"
      >
        <el-form-item label="考试名称" prop="examName">
          <el-input v-model="exportForm.examName" placeholder="请输入考试名称"></el-input>
        </el-form-item>
        <el-form-item label="考试时间" prop="examTime">
          <el-input v-model="exportForm.examTime" placeholder="请输入考试时间，如：2023年12月31日 13:30-15:30"></el-input>
        </el-form-item>
        <el-form-item label="答题时间" prop="duration">
          <el-input v-model="exportForm.duration" placeholder="请输入答题时间，如：120分钟"></el-input>
        </el-form-item>
        <el-form-item label="学校名称" prop="schoolName">
          <el-input v-model="exportForm.schoolName" placeholder="请输入学校名称"></el-input>
        </el-form-item>
        <el-form-item label="科目名称" prop="subjectName">
          <el-input v-model="exportForm.subjectName" placeholder="请输入科目名称"></el-input>
        </el-form-item>
        <el-form-item label="年级" prop="grade">
          <el-input v-model="exportForm.grade" placeholder="请输入年级"></el-input>
        </el-form-item>
        <el-form-item label="专业" prop="major">
          <el-input v-model="exportForm.major" placeholder="请输入专业"></el-input>
        </el-form-item>
        <el-form-item label="层次" prop="level">
          <el-input v-model="exportForm.level" placeholder="请输入层次"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="exportDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmExport" :loading="exportLoading">确认导出</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Download } from '@element-plus/icons-vue'
import { getSubjects } from '../../api/subject'
import { getPaperList, deletePaper, getPaperById } from '../../api/paper'
import { getQuestions } from '../../api/question'
import PaperPreview from '../../components/paper/PaperPreview.vue'
// 导入 Word 文档生成相关库
import { Document, Packer, Paragraph, TextRun, HeadingLevel, AlignmentType, Table, TableRow, TableCell, BorderStyle, WidthType, Header } from 'docx'
import { saveAs } from 'file-saver'

const router = useRouter()
const loading = ref(false)
const total = ref(0)
const paperList = ref([])
const subjects = ref([])

// 预览相关
const previewDialogVisible = ref(false)
const currentPaper = ref(null)
const currentQuestions = ref([])

// 表单数据
const paperForm = ref({
  subjectId: '',
  userId: JSON.parse(localStorage.getItem('user')).id,
  pageNum: 1,
  pageSize: 10
})

// 添加导出状态
const exportLoading = ref(false)
const exportingPaperId = ref(null)

// 添加导出对话框相关的状态
const exportDialogVisible = ref(false)
const exportFormRef = ref(null)
const currentExportPaper = ref(null)
const currentExportQuestions = ref([])

// 导出表单数据
const exportForm = ref({
  examName: '',
  examTime: '',
  duration: '',
  schoolName: '',
  subjectName: '',
  grade: '',
  major: '',
  level: ''
})

// 表单验证规则
const exportFormRules = {
  examName: [{ required: true, message: '请输入考试名称', trigger: 'blur' }],
  examTime: [{ required: true, message: '请输入考试时间', trigger: 'blur' }],
  duration: [{ required: true, message: '请输入答题时间', trigger: 'blur' }]
}

// 获取学科列表
const fetchSubjects = async () => {
  try {
    const userId = paperForm.value.userId
    const res = await getSubjects(userId, 1, 100)
    subjects.value = res.data.list
    
    // 如果有学科，默认选择第一个
    if (subjects.value.length > 0) {
      paperForm.value.subjectId = subjects.value[2].id
      fetchPaperList()
    }
  } catch (error) {
    ElMessage.error('获取学科列表失败')
  }
}

// 获取试卷列表
const fetchPaperList = async () => {
  if (!paperForm.value.subjectId) return
  
  loading.value = true
  try {
    const res = await getPaperList({
      userId: paperForm.value.userId,
      subjectId: paperForm.value.subjectId,
      pageNum: paperForm.value.pageNum,
      pageSize: paperForm.value.pageSize
    })
    
    paperList.value = res.data.list
    total.value = res.data.total
  } catch (error) {
    ElMessage.error('获取试卷列表失败')
  } finally {
    loading.value = false
  }
}

// 学科变更
const handleSubjectChange = () => {
  paperForm.value.pageNum = 1
  fetchPaperList()
}

// 页码变更
const handleCurrentChange = (val) => {
  paperForm.value.pageNum = val
  fetchPaperList()
}

// 每页条数变更
const handleSizeChange = (val) => {
  paperForm.value.pageSize = val
  paperForm.value.pageNum = 1
  fetchPaperList()
}

// 创建试卷
const handleCreatePaper = () => {
  if (!paperForm.value.subjectId) {
    ElMessage.warning('请先选择学科')
    return
  }
  router.push({
    path: '/paper/create'
  })
}

// 查看试卷（预览）
const handleViewPaper = async (paper) => {
  try {
    loading.value = true
    
    // 设置当前试卷
    currentPaper.value = {
      ...paper,
      name: paper.paperName, // 适配预览组件的属性名
      typeSet: 'auto' // 默认按题型分类显示
    }
    
    // 获取试卷包含的题目
    if (paper.questionIds) {
      const questionIds = paper.questionIds.split(',')
      const res = await getQuestions(questionIds)
      if (res.data) {
        currentQuestions.value = res.data
      } else {
        currentQuestions.value = []
      }
    } else {
      currentQuestions.value = []
    }
    
    // 显示预览对话框
    previewDialogVisible.value = true
  } catch (error) {
    ElMessage.error('获取试卷数据失败')
    console.error(error)
  } finally {
    loading.value = false
  }
}

// 编辑试卷
const handleEditPaper = (paper) => {
  previewDialogVisible.value = false
  router.push({
    path: `/create/manual`,
    query:{
      paperId: paper.paperId
    }
  })
}

// 删除试卷
const handleDeletePaper = async (paperId) => {
  try {
    await deletePaper(paperId)
    ElMessage.success('删除成功')
    fetchPaperList()
  } catch (error) {
    ElMessage.error('删除失败')
  }
}

// 获取试题类型展示
const getQuestionTypes = (typeSet) => {
  if (!typeSet) return []
  
  const typeMap = {
    'SINGLE_CHOICE': '单选题',
    'MULTIPLE_CHOICE': '多选题',
    'TRUE_FALSE': '判断题',
    'FILL_BLANK': '填空题',
    'SHORT_ANSWER': '简答题',
    'READING': '阅读理解'
  }
  
  return typeSet.split(',').map(type => typeMap[type] || type)
}

// 获取难度显示文本
const getDifficultyText = (difficulty) => {
  const difficultyMap = {
    'easy': '简单',
    'medium': '中等',
    'hard': '困难'
  }
  return difficultyMap[difficulty] || '未知'
}

// 获取难度标签类型
const getDifficultyTag = (difficulty) => {
  const tagMap = {
    'easy': 'success',
    'medium': 'warning',
    'hard': 'danger'
  }
  return tagMap[difficulty] || 'info'
}

// 修改导出函数 - 先显示信息输入对话框
const handleexportPaper = async (paper) => {
  try {
    // 设置加载状态
    exportingPaperId.value = paper.paperId
    ElMessage.info('正在准备导出，请稍候...')
    
    // 获取试卷包含的题目
    if (!paper.questionIds) {
      ElMessage.warning('试卷中没有题目')
      return
    }
    
    // 解析题目ID，过滤无效ID
    const questionIds = paper.questionIds.split(',').filter(id => id && id.trim())
    if (questionIds.length === 0) {
      ElMessage.warning('试卷中没有有效题目ID')
      return
    }
    
    ElMessage.info('正在获取题目数据...')
    const res = await getQuestions(questionIds)
    if (!res.data || res.data.length === 0) {
      ElMessage.warning('获取题目数据失败')
      return
    }
    
    // 过滤无效题目
    const questions = res.data.filter(q => q && q.questionType)
    if (questions.length === 0) {
      ElMessage.warning('没有有效的题目数据')
      return
    }
    
    // 设置当前要导出的试卷和题目
    currentExportPaper.value = paper
    currentExportQuestions.value = questions
    
    // 初始化导出表单数据
    const subjectObj = subjects.value.find(s => s.id === paper.subjectId) || {}
    exportForm.value = {
      examName: paper.paperName || '期末考试',
      examTime: new Date().toLocaleDateString(),
      duration: '120分钟',
      schoolName: '某大学',
      subjectName: subjectObj.name || '计算机科学',
      grade: '2023级',
      major: '计算机科学与技术',
      level: '本科'
    }
    
    // 显示导出信息输入对话框
    exportDialogVisible.value = true
    
  } catch (error) {
    ElMessage.error('导出准备失败：' + (error.message || '未知错误'))
    console.error('导出准备失败:', error)
    exportingPaperId.value = null
  }
}

// 确认导出，生成Word文档
const confirmExport = async () => {
  if (!exportFormRef.value) return
  
  try {
    // 表单验证
    await exportFormRef.value.validate()
    
    // 设置加载状态
    exportLoading.value = true
    
    // 生成Word文档
    ElMessage.info('正在生成Word文档...')
    await generateWordDocument(currentExportPaper.value, currentExportQuestions.value, exportForm.value)
    
    ElMessage.success('试卷已成功导出为Word文档')
    exportDialogVisible.value = false
  } catch (error) {
    if (error === false) {
      // 表单验证失败
      ElMessage.warning('请完善必填信息')
    } else {
      ElMessage.error('导出失败：' + (error.message || '未知错误'))
      console.error('导出失败:', error)
    }
  } finally {
    exportLoading.value = false
    exportingPaperId.value = null
  }
}

// 修改生成Word文档函数，解决第一页空白和页眉问题
const generateWordDocument = async (paper, questions, formData) => {
  try {
    // 确保有有效的题目
    if (!questions || questions.length === 0) {
      ElMessage.warning('试卷中没有有效题目')
      return
    }
    
    // 计算总分
    const totalScore = questions.reduce((sum, q) => {
      const score = parseInt(q.score) || getDefaultScore(q.questionType)
      return sum + score
    }, 0)
    
    // 准备添加到文档的内容（先收集所有内容，再一次性添加）
    const docContent = []
    
    // 添加标题和页眉信息直接作为文档内容（不使用页眉功能）
    docContent.push(
      // 第一行标题（居中）- 宋体小二
      new Paragraph({
        children: [
          new TextRun({ 
            text: `${formData.schoolName}  ${formData.subjectName}  试题`,
            bold: true,
            size: 32, // 小二号字体大约32磅
            font: "SimSun" // 宋体
          })
        ],
        alignment: AlignmentType.CENTER,
        spacing: { after: 200 },
      }),
      
      // 第二行信息 - 宋体四号
      new Paragraph({
        children: [
          new TextRun({ 
            text: `年级：${formData.grade}  专业：${formData.major}  层次：${formData.level}  学号________  姓名________  考试时间：${formData.examTime}`,
            size: 14, // 四号字体大约14磅
            font: "SimSun" // 宋体
          })
        ],
        spacing: { after: 200 },
      }),
      
      // 分隔线
      new Paragraph({
        text: "_______________________________________________________________________",
        alignment: AlignmentType.CENTER,
        spacing: { after: 400 },
      })
    )
    
    // 按题型分类并添加题目
    const questionTypes = [
      { value: 'SINGLE_CHOICE', label: '一、单项选择题', explain: '（${count}题×1分=${total}分）' },
      { value: 'MULTIPLE_CHOICE', label: '二、不定项选择题', explain: '（${count}题×2分=${total}分）' },
      { value: 'TRUE_FALSE', label: '三、判断题', explain: '（${count}题×1分=${total}分）' },
      { value: 'FILL_BLANK', label: '四、填空题', explain: '（${count}题×5分=${total}分）' },
      { value: 'SHORT_ANSWER', label: '五、简答题', explain: '（${count}题×6分=${total}分）' },
      { value: 'READING', label: '六、阅读理解', explain: '（${count}题×10分=${total}分）' }
    ]
    
    // 分类题目
    const questionsByType = {}
    questionTypes.forEach(type => {
      questionsByType[type.value] = questions.filter(q => q && q.questionType === type.value)
    })
    
    // 添加各题型到文档
    questionTypes.forEach(type => {
      const typedQuestions = questionsByType[type.value] || []
      if (typedQuestions.length > 0) {
        try {
          // 计算该题型的总分
          const typeScore = typedQuestions.reduce((sum, q) => {
            const score = parseInt(q.score) || getDefaultScore(type.value)
            return sum + score
          }, 0)
          
          // 替换解释文本中的变量
          const explainText = type.explain
            .replace('${count}', typedQuestions.length)
            .replace('${total}', typeScore)
          
          // 添加题型标题（使用蓝色）- 字体调大
          docContent.push(
            new Paragraph({
              children: [
                new TextRun({ 
                  text: `${type.label}${explainText}`,
                  bold: true,
                  color: '#0000FF',
                  size: 14, // 增大到 14 磅
                  font: "SimSun" // 宋体
                }),
              ],
              spacing: { before: 300, after: 200 },
            })
          )
          
          // 收集该题型的所有题目
          typedQuestions.forEach((question, index) => {
            if (question) {
              try {
                // 收集题目内容 - 宋体五号
                const questionContent = collectQuestionContent(question, index + 1, type.value)
                docContent.push(...questionContent)
              } catch (error) {
                console.error(`处理第 ${index + 1} 题(${type.label})失败:`, error)
              }
            }
          })
        } catch (error) {
          console.error(`处理 ${type.label} 失败:`, error)
        }
      }
    })
    
    // 创建文档（不使用页眉，而是直接添加内容）
    const doc = new Document({
      sections: [{
        properties: {
          page: {
            margin: {
              top: 1000,
              right: 1000,
              bottom: 1000,
              left: 1000,
            },
          },
        },
        children: docContent,
      }],
    });
    
    // 使用 toBlob 而不是 toBuffer
    const blob = await Packer.toBlob(doc)
    saveAs(blob, `${paper.paperName || '未命名试卷'}.docx`)
  } catch (error) {
    console.error('生成Word文档失败:', error)
    throw new Error('生成Word文档失败: ' + error.message)
  }
}

// 题目内容收集函数 - 增大字体并去除答案区域
const collectQuestionContent = (question, index, questionType) => {
  const content = []
  
  // 防止 null 或 undefined 值
  const safeText = (text) => {
    return text ? text.toString() : ''
  }
  
  // 题目分数
  const score = question.score || getDefaultScore(questionType)
  
  // 题目标题和题干 - 宋体五号，调整为更大字号
  if (questionType === 'READING') {
    // 阅读理解题显示阅读文章
    content.push(
      new Paragraph({
        children: [
          new TextRun({ 
            text: `${index}. `,
            bold: true,
            size: 12, // 增大到 12 磅
            font: "SimSun" // 宋体
          }),
          new TextRun({ 
            text: safeText(question.passage),
            size: 12, // 增大到 12 磅
            font: "SimSun" // 宋体
          })
        ],
        spacing: { before: 120, after: 120 },
      })
    )
  } else {
    // 普通题目显示题干
    content.push(
      new Paragraph({
        children: [
          new TextRun({ 
            text: `${index}. `,
            bold: true,
            size: 12, // 增大到 12 磅
            font: "SimSun" // 宋体
          }),
          new TextRun({ 
            text: safeText(question.stem),
            size: 12, // 增大到 12 磅
            font: "SimSun" // 宋体
          })
        ],
        spacing: { before: 120, after: 120 },
      })
    )
  }
  
  // 处理不同题型 - 所有选项都使用更大字号，但不添加答案区域
  if (['SINGLE_CHOICE', 'MULTIPLE_CHOICE'].includes(questionType)) {
    // 选择题选项
    if (question.options && question.options.length > 0) {
      question.options.forEach(option => {
        if (option && option.optionId && option.content) {
          content.push(
            new Paragraph({
              children: [
                new TextRun({ 
                  text: `${safeText(option.optionId)}. ${safeText(option.content)}`,
                  size: 12, // 增大到 12 磅
                  font: "SimSun" // 宋体
                }),
              ],
              indent: { left: 400 },
              spacing: { after: 100 },
            })
          )
        }
      })
    }
    
    // 移除选择题答案填写区
  } else if (questionType === 'TRUE_FALSE') {
    // 不添加判断题答案填写区
  } else if (questionType === 'FILL_BLANK') {
    // 不添加填空题答案填写区
  } else if (questionType === 'SHORT_ANSWER') {
    // 不添加简答题答案填写区
  } else if (questionType === 'READING') {
    // 阅读理解子题目
    if (question.subQuestions && question.subQuestions.length > 0) {
      question.subQuestions.forEach((subQ, subIndex) => {
        if (subQ) {
          // 子题目题干
          content.push(
            new Paragraph({
              children: [
                new TextRun({ 
                  text: `(${subIndex + 1}) `,
                  bold: true,
                  size: 12, // 增大到 12 磅
                  font: "SimSun" // 宋体
                }),
                new TextRun({ 
                  text: safeText(subQ.stem),
                  size: 12, // 增大到 12 磅
                  font: "SimSun" // 宋体
                })
              ],
              indent: { left: 400 },
              spacing: { before: 100, after: 80 },
            })
          )
          
          // 子题目选项
          if (['SINGLE_CHOICE', 'MULTIPLE_CHOICE'].includes(subQ.questionType) && subQ.options) {
            subQ.options.forEach(option => {
              if (option && option.optionId && option.content) {
                content.push(
                  new Paragraph({
                    children: [
                      new TextRun({ 
                        text: `${safeText(option.optionId)}. ${safeText(option.content)}`,
                        size: 12, // 增大到 12 磅
                        font: "SimSun" // 宋体
                      }),
                    ],
                    indent: { left: 600 },
                    spacing: { after: 100 },
                  })
                )
              }
            })
          }
          
          // 移除子题目答案填写区
        }
      })
    }
  }
  
  return content
}

// 获取默认分数
const getDefaultScore = (questionType) => {
  const scoreMap = {
    'SINGLE_CHOICE': 1,
    'MULTIPLE_CHOICE': 2,
    'TRUE_FALSE': 1,
    'FILL_BLANK': 5,
    'SHORT_ANSWER': 6,
    'READING': 10
  }
  return scoreMap[questionType] || 0
}

onMounted(() => {
  fetchSubjects()
})
</script>

<style scoped>
.paper-list-container {
  display: flex;
  flex-direction: column;
  background: #ffffff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  height: 100%;
}

.paper-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  border-bottom: 1px solid #f0f0f0;
}

.paper-tools {
  display: flex;
  align-items: center;
  gap: 16px;
}

.subject-select {
  width: 180px;
}

.paper-content {
  padding: 20px;
  flex: 1;
  overflow: auto;
}

.paper-name {
  font-weight: 500;
  color: #333;
}

.question-types {
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
}

.question-type-tag {
  margin-right: 5px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

/* 适配暗色模式 */
:deep(.el-empty) {
  padding: 40px 0;
}

/* 添加预览对话框相关样式 */
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 20px;
}
</style>